package com.hongning.railway.data.http;

import android.app.Activity;
import android.content.Intent;

import com.hongning.railway.entity.LoginEntity;
import com.hongning.railway.ui.login.LoginActivity;
import com.hongning.railway.util.Apputils;
import com.hongning.railway.util.GsonUtil;

import java.io.IOException;

import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request()
                .newBuilder();
        LoginEntity loginEntity = Apputils.getLoginInfo();
        if (loginEntity!=null){
            builder.addHeader("token",loginEntity.getToken());
        }
        ResponseBody body=null;
        Response response = chain.proceed(builder.build());

        try {
            String string = response.body().string();
            BaseResponse result = GsonUtil.GsonToBean(string,BaseResponse.class);
            body = ResponseBody.create(response.body().contentType(), string);
            if (result.getCode() == 101){
    //            ToastUtils.showShort("登录失效，请重新登录");
                Apputils.clearLoginInfo();
                Activity current = AppManager.getAppManager().currentActivity();
                Intent intent = new Intent(current, LoginActivity.class);
                current.startActivity(intent);
                current.finish();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.newBuilder().body(body).build();
    }


}
